/**
 * 音频上下文单例
 * 确保整个应用中只有一个AudioContext实例，避免多个实例冲突
 */

class AudioContextSingleton {
    constructor() {
        this.audioContext = null;
    }

    /**
     * 获取音频上下文实例
     * @param {Object} options - 音频上下文配置选项
     * @returns {AudioContext} 音频上下文实例
     */
    getContext(options = {}) {
        if (!this.audioContext) {
            const defaultOptions = {
                sampleRate: 48000,
                latencyHint: 'interactive'
            };
            
            const contextOptions = { ...defaultOptions, ...options };
            
            try {
                this.audioContext = new (window.AudioContext || window.webkitAudioContext)(contextOptions);
                console.log('🎵 创建音频上下文单例');
                
                // 监听状态变化
                this.audioContext.addEventListener('statechange', () => {
                    console.log(`🎵 音频上下文状态变化: ${this.audioContext.state}`);
                });
            } catch (error) {
                console.error('❌ 创建音频上下文失败:', error);
                throw error;
            }
        }
        
        return this.audioContext;
    }

    /**
     * 确保音频上下文处于活动状态
     */
    async resume() {
        if (this.audioContext && this.audioContext.state === 'suspended') {
            try {
                await this.audioContext.resume();
                console.log('🎵 音频上下文已恢复');
            } catch (error) {
                console.error('❌ 恢复音频上下文失败:', error);
            }
        }
    }

    /**
     * 暂停音频上下文
     */
    async suspend() {
        if (this.audioContext && this.audioContext.state === 'running') {
            try {
                await this.audioContext.suspend();
                console.log('🎵 音频上下文已暂停');
            } catch (error) {
                console.error('❌ 暂停音频上下文失败:', error);
            }
        }
    }

    /**
     * 关闭音频上下文（仅在不再需要时调用）
     */
    async close() {
        if (this.audioContext && this.audioContext.state !== 'closed') {
            try {
                await this.audioContext.close();
                this.audioContext = null;
                console.log('🎵 音频上下文已关闭');
            } catch (error) {
                console.error('❌ 关闭音频上下文失败:', error);
            }
        }
    }
}

// 创建并导出单例实例
const audioContextSingleton = new AudioContextSingleton();
export default audioContextSingleton;